var mysql = require('mysql');
var common = require('../util/common');
var mysqlConfig = require('../../config/mysql.json');

module.exports = function() {
    return new Handler();
};

var Handler = function() {
    var config = {
        "host": mysqlConfig.host,
        "port": mysqlConfig.port,
        "user": mysqlConfig.user,
        "password": mysqlConfig.password,
        "database": mysqlConfig.database,
        "connectionLimit": mysqlConfig.connectionLimit || 2
    };
    // supportBigNumbers: When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option (Default: false).
    config.supportBigNumbers = true;
    // bigNumberStrings: Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: false).
    config.bigNumberStrings = true;
    this.db = mysql.createPool(config);
    this.db.on('connection', function(connection) {
        connection.query('SET SESSION sql_mode = \'STRICT_TRANS_TABLES\'');
    });
};

Handler.prototype.asyncGetConnection = function(cb) {
    this.db.getConnection(cb)
};
/**
 * note: must called inside a fiber
 */
Handler.prototype.syncGetConnection = function() {
    return common.forMethod(this.db, 'getConnection');
};

Handler.prototype.asyncQuery = function(conn) {
    conn.query.apply(conn, Array.prototype.slice.call(arguments, 1));
};

/**
 * note: must called inside a fiber
 */
Handler.prototype.syncQuery = function(conn) {
    var newargs = Array.prototype.slice.call(arguments, 1);
    newargs.unshift(conn, 'query');
    return common.forMethod.apply(null, newargs);
};